package com.yashi.service.impl;


import java.security.SecureRandom;
import java.util.List;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yashi.dao.TbUserMapper;
import com.yashi.entity.TbUser;
import com.yashi.service.UserService;
import com.yashi.utils.YSUtils;

@Service
public class UserServiceImpl implements UserService {
	
	@Autowired
	private TbUserMapper userDao;
	
	/**
	 * 密码加密
	 */
	private static final byte[] DES_KEY = { 21, 1, -110, 82, -32, -85, -128, -65 };
    @SuppressWarnings("restriction")
    public static String encryptBasedDes(String data) {
        String encryptedData = null;
        try {
            // DES算法要求有一个可信  任的随机数源
            SecureRandom sr = new SecureRandom();
            DESKeySpec deskey = new DESKeySpec(DES_KEY);
            // 创建一个密匙工厂，然后用它把DESKeySpec转换成一个SecretKey对象
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey key = keyFactory.generateSecret(deskey);
            // 加密对象
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, key, sr);
            // 加密，并把字节数组编码成字符串
            encryptedData = new sun.misc.BASE64Encoder().encode(cipher.doFinal(data.getBytes()));
        } catch (Exception e) {
            // log.error("加密错误，错误信息：", e);
            throw new RuntimeException("加密错误，错误信息：", e);
        }
        return encryptedData;
    }
    /**
     * 解密
     * @param cryptData
     * @return
     */
    @SuppressWarnings("restriction")
    public static String decryptBasedDes(String cryptData) {
        String decryptedData = null;
        try {
            // DES算法要求有一个可信任的随机数源
            SecureRandom sr = new SecureRandom();
            DESKeySpec deskey = new DESKeySpec(DES_KEY);
            // 创建一个密匙工厂，然后用它把DESKeySpec转换成一个SecretKey对象
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey key = keyFactory.generateSecret(deskey);
            // 解密对象
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, key, sr);
            // 把字符串进行解码，解码为为字节数组，并解密
            decryptedData = new String(cipher.doFinal(new sun.misc.BASE64Decoder().decodeBuffer(cryptData)));
        } catch (Exception e) {
            throw new RuntimeException("解密错误，错误信息：", e);
        }
        return decryptedData;
    }
	
	
	/**
	 * app登录验证
	 */
	@SuppressWarnings("unused")
	@Override
	public TbUser selectByUser(TbUser user) throws Exception {
		//接收前台传过来的用户名和密码
		String username = user.getUsername();
		String password = user.getPassword();
		TbUser selectByUser = userDao.selectByUserName(username);
		String findPassword = selectByUser.getPassword();
		
		//判断用户名和密码是否正确
		if(selectByUser==null){
			throw new Exception("用户名或密码错误");
		}else{
			if(password.equals(decryptBasedDes(findPassword))){
				System.out.println("app端登陆成功");
				return selectByUser;
			}else{
				throw new Exception("用户名或密码错误");
			}
		}
		
	}

	/**
	 * 添加用户
	 * @throws Exception 
	 */
	@Override
	public Integer addUser(TbUser user,HttpServletRequest request, HttpSession session) throws Exception {
			//设置id
			user.setId(YSUtils.getUUID());
			//设置创建时间
			user.setCreateDate(YSUtils.getCurrentTime());
			//设置是否存在  0：存在 1：不存在
			user.setDelFlag("0");
			//获取创建人
			TbUser user1 = (TbUser) session.getAttribute("user");
			user.setCreateBy(user1.getUsername());
//			//添加默认初始头像
			
			//设置是否是管理员
			user.setIsAdmin("0");
			String path = request.getContextPath();
			String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/headImg/";
			user.setPhoto(basePath+"0e166d3e786e41cf97a240cb79ce4b19.jpg");
			//密码加密
			user.setPassword(encryptBasedDes(user.getPassword()));
			//判断用户的重复性（根据用户名查询）
			Integer findByUserName = userDao.findByUserName(user.getUsername());
			Integer count = null;
			if(findByUserName>0){
				throw new Exception("用户名已经存在");
			}else{
				count = userDao.insertSelective(user);
				return count;
			}
		
		
		
	}

	/**
	 * 查询所有用户
	 * @throws Exception 
	 */
	@Override
	public PageInfo<TbUser> findUserList(Integer pageNum) throws Exception {
		PageHelper.startPage(pageNum, 5);
		List<TbUser> findUserList = userDao.findUserList();
		PageInfo<TbUser> page = new PageInfo<TbUser>(findUserList);
		return page;
	}

	/**
	 * 修改用户信息
	 * @throws Exception 
	 */
	@Override
	public Integer updateUser(TbUser user,HttpSession session) throws Exception {
//		//设置修改人
//		TbUser user1 = (TbUser) session.getAttribute("user");
//		user.setUpdateBy(user1.getUsername());
		//设置修改日期
		user.setUpdateDate(YSUtils.getCurrentTime());
		int updateCount = userDao.updateByPrimaryKeySelective(user);
		if(updateCount>0){
			return updateCount;
		}else{
			throw new Exception("更新失败");
		}
		
	}

	@Override
	public Integer deleteUser(TbUser user) throws Exception {
		user.setDelFlag("1");
		Integer deleteUser = userDao.deleteUser(user);
		if(deleteUser>0){
			return deleteUser;
		}else{
			throw new Exception("删除失败");
		}
		
	}

	/**
	 * 根据id来查询
	 * @throws Exception 
	 */
	@Override
	public TbUser selectUserById(String userId) throws Exception {
		TbUser user = userDao.selectByPrimaryKey(userId);
		if(user!=null){
			return user;
		}else{
			throw new Exception("查找到用户不存在");
		}
	}

	/**
	 * 根据用户名模糊查询
	 */
	@Override
	public PageInfo<TbUser> selectUserByName(String userName,Integer pageNum) throws Exception {
		PageHelper.startPage(pageNum, 5);
		List<TbUser> findUserList = userDao.selectUserByName(userName);
		PageInfo<TbUser> page= new PageInfo<TbUser>(findUserList);
		return page;
	}

	/**
	 * 更新密码
	 */
	
	@Override
	public Integer updatePass(String userId, String oldPassword, String newPassword,String confirmPass) throws Exception {
		TbUser tbUser = userDao.selectByPrimaryKey(userId);
		if(!newPassword.equals(confirmPass)){
			throw new Exception("前后两次输入的密码不一致");
		}else{
			if(oldPassword.equals(decryptBasedDes(tbUser.getPassword()))){
				
				Integer updatePass = userDao.updatePass(userId,encryptBasedDes(newPassword));
				return updatePass;
			}else{
				throw new Exception("输入的原密码不正确");
			}
		}
		
	}

	@Override
	public List<TbUser> findUserChatList(HttpSession session) {
		TbUser user = (TbUser) session.getAttribute("user");
		List<TbUser> userList = userDao.findUserChatList(user.getId());
		return userList;
	}

	@Override
	public String modifyImg(String userId, MultipartFile file, HttpServletRequest request,HttpSession session) {
        //获取文件的后缀名
        String fileNameSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //重新拼接文件名
        String fileName=YSUtils.getFileCurrentTime()+userId+fileNameSuffix;
        String path = request.getContextPath();
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/headImg/";
        String filePath = request.getSession().getServletContext().getRealPath("/headImg/");
        //拼接返回文件的地址
        String url =basePath+fileName;
        try {
            YSUtils.uploadFile(file.getBytes(), filePath, fileName);
            userDao.modifyImg(userId,url);
        } catch (Exception e) {
        }
		return url;
	}
	/**
	 * App端查询所有用户
	 */
	@Override
	public List<TbUser> findUserList1() {
		List<TbUser> findUserList = userDao.findUserList();
		return findUserList;
	}
	
	/**
	 * App端模糊查询
	 */
	@Override
	public List<TbUser> selectUserByName1(TbUser user) {
		List<TbUser> selectUserByName = userDao.selectUserByName(user.getUsername());
		return selectUserByName;
		
	}
	@Override
	public TbUser findUserById(String userId) {
		TbUser user = userDao.selectByPrimaryKey(userId);
		return user;
	}
	
	/**
	 * 设为管理员
	 */
	@Override
	public TbUser addAdmin(TbUser user) {
//		user.setIsAdmin("1");
		userDao.updateAdmin(user);
		return user;
	}
	/**
	 * web端登陆验证
	 * @throws Exception 
	 */
	@SuppressWarnings("unused")
	@Override
	public TbUser selectByUser1(TbUser user) throws Exception {
		//接收前台传过来的用户名和密码
				String username = user.getUsername();
				String password = user.getPassword();
				TbUser selectByUser = userDao.selectByUserName(username);
				String findPassword = selectByUser.getPassword();
				
				//判断用户名和密码是否正确
				if(selectByUser==null){
					throw new Exception("用户名或密码错误");
				}else{
					if("1".equals(selectByUser.getIsAdmin()) && password.equals(decryptBasedDes(findPassword))){
						System.out.println("web端登陆成功");
						return selectByUser;
					}else{
						throw new Exception("用户名或密码错误");
					}
				}
	}

}
